package com.czkt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czkt.pojo.Cart;
import com.czkt.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class CartController {
    @Autowired
    CartService cartService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping("/cart/list")
    public Object CartList(Integer uid) {
        return cartService.cartList(uid);
    }

    @RequestMapping("/cart/add")
    public Object CartAdd(Cart cart) {
        boolean flg = false;
        Long uid = Long.valueOf(redisTemplate.opsForValue().get("uid"));
        if (cart.getUserId() != uid) {
            flg = cartService.save(cart);
        } else {
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(Cart::getUserId, cart.getUserId())
                    .eq(Cart::getSkuId, cart.getSkuId())
                    .eq(Cart::getShopId, cart.getShopId());
            flg = cartService.saveOrUpdate(cart, queryWrapper);
        }
        return flg;
    }

    @RequestMapping("/cart/count")
    public Object cartCount(Integer uid) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.lambda().eq(Cart::getUserId, uid);
        List<Cart> cart = cartService.list(cartQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("ListCart", cart);
        map.put("count", cartService.count(cartQueryWrapper));
        return map;
    }

    @RequestMapping("/cart/delect")
    public Object cartDelect(Integer cartId) {
        System.out.println("cartId：" + cartId);
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.lambda().eq(Cart::getCartId, cartId);
        return cartService.remove(cartQueryWrapper);
    }

    /**
     * 根据id更新数量
     *
     * @param cartId  前端传递的id
     * @param numbers 前端传递的熟料
     * @return
     */
    @RequestMapping("/cart/update")
    public Object cartUpdate(Integer cartId, Integer numbers) {
        return cartService.updateCart(numbers, cartId);
    }
}

